/**
 * AI模块
 * 负责AI模型选择、API Key管理和本地存储功能
 */

// 本地存储键名
export const STORAGE_KEYS = {
    API_KEY: 'ai_api_key',
    AI_PROVIDER: 'ai_provider',
    AI_MODEL: 'ai_model'
};

// AI模型数据
export const aiModels = {
    alibaba: [
        { value: 'qwen3-vl-plus', label: '通义千问3-VL-Plus' },
        { value: 'qwen3-vl-flash', label: '通义千问3-VL-Flash' },
        { value: 'qwen-vl-max', label: '通义千问VL-Max' }
    ]
};

/**
 * 更新AI模型选项
 * @param {HTMLSelectElement} providerSelect - 厂商选择器
 * @param {HTMLSelectElement} modelSelect - 模型选择器
 * @param {Object} models - 模型数据对象
 */
export function updateAiModels(providerSelect, modelSelect, models) {
    const selectedProvider = providerSelect.value;
    
    // 清空现有选项
    modelSelect.innerHTML = '';
    
    if (selectedProvider && models[selectedProvider]) {
        // 启用模型选择器
        modelSelect.disabled = false;
        
        // 添加默认选项
        const defaultOption = document.createElement('option');
        defaultOption.value = '';
        defaultOption.textContent = '请选择模型';
        modelSelect.appendChild(defaultOption);
        
        // 添加模型选项
        models[selectedProvider].forEach(model => {
            const option = document.createElement('option');
            option.value = model.value;
            option.textContent = model.label;
            modelSelect.appendChild(option);
        });
    } else {
        // 禁用模型选择器
        modelSelect.disabled = true;
        const defaultOption = document.createElement('option');
        defaultOption.value = '';
        defaultOption.textContent = '请先选择厂商';
        modelSelect.appendChild(defaultOption);
    }
}

/**
 * 保存API Key到本地存储
 * @param {HTMLInputElement} apiKeyInput - API Key输入框
 */
export function saveApiKeyToStorage(apiKeyInput) {
    const apiKey = apiKeyInput.value.trim();
    if (apiKey) {
        localStorage.setItem(STORAGE_KEYS.API_KEY, apiKey);
    } else {
        localStorage.removeItem(STORAGE_KEYS.API_KEY);
    }
}

/**
 * 保存AI厂商到本地存储
 * @param {HTMLSelectElement} providerSelect - 厂商选择器
 */
export function saveAiProviderToStorage(providerSelect) {
    const provider = providerSelect.value;
    if (provider) {
        localStorage.setItem(STORAGE_KEYS.AI_PROVIDER, provider);
    } else {
        localStorage.removeItem(STORAGE_KEYS.AI_PROVIDER);
    }
}

/**
 * 保存AI模型到本地存储
 * @param {HTMLSelectElement} modelSelect - 模型选择器
 */
export function saveAiModelToStorage(modelSelect) {
    const model = modelSelect.value;
    if (model) {
        localStorage.setItem(STORAGE_KEYS.AI_MODEL, model);
    } else {
        localStorage.removeItem(STORAGE_KEYS.AI_MODEL);
    }
}

/**
 * 从本地存储加载设置
 * @param {HTMLInputElement} apiKeyInput - API Key输入框
 * @param {HTMLSelectElement} providerSelect - 厂商选择器
 * @param {HTMLSelectElement} modelSelect - 模型选择器
 * @param {Function} updateModelsFn - 更新模型选项的函数
 */
export function loadSettingsFromStorage(apiKeyInput, providerSelect, modelSelect, updateModelsFn) {
    // 加载API Key
    const savedApiKey = localStorage.getItem(STORAGE_KEYS.API_KEY);
    if (savedApiKey) {
        apiKeyInput.value = savedApiKey;
    }
    
    // 加载AI厂商和模型
    const savedProvider = localStorage.getItem(STORAGE_KEYS.AI_PROVIDER);
    if (savedProvider) {
        providerSelect.value = savedProvider;
        updateModelsFn();
        
        const savedModel = localStorage.getItem(STORAGE_KEYS.AI_MODEL);
        if (savedModel) {
            // 等待模型选项更新后再设置值
            setTimeout(() => {
                modelSelect.value = savedModel;
            }, 100);
        }
    }
}

/**
 * 获取当前保存的API Key
 * @returns {string|null} API Key
 */
export function getApiKey() {
    return localStorage.getItem(STORAGE_KEYS.API_KEY);
}

/**
 * 获取当前保存的AI厂商
 * @returns {string|null} AI厂商
 */
export function getAiProvider() {
    return localStorage.getItem(STORAGE_KEYS.AI_PROVIDER);
}

/**
 * 获取当前保存的AI模型
 * @returns {string|null} AI模型
 */
export function getAiModel() {
    return localStorage.getItem(STORAGE_KEYS.AI_MODEL);
}

/**
 * 初始化AI模块
 * @param {Object} elements - UI元素对象
 * @param {HTMLInputElement} elements.apiKeyInput - API Key输入框
 * @param {HTMLSelectElement} elements.providerSelect - 厂商选择器
 * @param {HTMLSelectElement} elements.modelSelect - 模型选择器
 */
export function initAiModule(elements) {
    const { apiKeyInput, providerSelect, modelSelect } = elements;
    
    // 更新模型选项的包装函数
    const updateModelsFn = () => {
        updateAiModels(providerSelect, modelSelect, aiModels);
    };
    
    // 保存函数的包装函数
    const saveApiKey = () => saveApiKeyToStorage(apiKeyInput);
    const saveProvider = () => {
        saveAiProviderToStorage(providerSelect);
        updateModelsFn();
    };
    const saveModel = () => saveAiModelToStorage(modelSelect);
    
    // 监听API Key输入变化（实时保存）
    apiKeyInput.addEventListener('input', saveApiKey);
    
    // 监听AI厂商选择变化
    providerSelect.addEventListener('change', saveProvider);
    
    // 监听AI模型选择变化
    modelSelect.addEventListener('change', saveModel);
    
    // 如果厂商选择器已经有值，先更新模型列表
    if (providerSelect.value) {
        updateModelsFn();
    }
    
    // 页面加载时从本地存储恢复设置
    loadSettingsFromStorage(apiKeyInput, providerSelect, modelSelect, updateModelsFn);
}

